package com.rocky.component.elasticsearch;

import com.rocky.component.util.ObjectMapperUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author rocky
 * date 2025-07-17
 * Description:
 */
@RestController
@RequestMapping("/matchAllQuery")
public class MatchAllQueryExample {

    private final RestHighLevelClient restHighLevelClient;

    public MatchAllQueryExample(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @GetMapping("/matchAllQuery")
    public String matchAllQuery() throws IOException {
        // match_all
        MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        // sort
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("account_number").order(SortOrder.ASC);

        // body
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .query(queryBuilder)
                .sort(sortBuilder)
                .from(0)
                .size(10);

        // _search
        SearchRequest searchRequest = new SearchRequest("bank")
                .source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        return ObjectMapperUtil.get().writeValueAsString(searchResponse);
    }
}
